package tinglema.server.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tinglema.server.service.ObjectStoreService;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author delucia
 * @version 1.0.0
 * @date 2025-05-12
 * @apiNote OSS服务接口实现类
 */
@Service
public class ObjectStoreServiceImpl implements ObjectStoreService {

    @Resource
    private OSS ossClient;

    @Value("${aliyun.oss.bucketName}")
    private String BUCKET_NAME;
    @Value("${aliyun.oss.endPoint}")
    private String ENDPOINT;


    @Override
    public String uploadFile(String dirName, String objectName, MultipartFile file) throws IOException {
        String fullObjectName = dirName + "/" + objectName;
        PutObjectResult result = ossClient.putObject(BUCKET_NAME, fullObjectName, file.getInputStream());
        return getAccessibleUrl(result.getETag(), fullObjectName);
    }


    private String getAccessibleUrl(String eTag, String objectName) {
        return "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + objectName;
    }
}
